/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Yongke
 */
@WebServlet(name="login", urlPatterns={"/login"})
public class login extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Logging In</title>");
            out.println("<link rel='StyleSheet' href='redirect.css' type='text/css' />");
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/myrc","progin","progin");
            stmt = (Statement) conn.createStatement();
            PreparedStatement ps = null;
            String query = "SELECT * FROM user WHERE (Username='" + request.getParameter("username")
                    + "' AND Password='" + request.getParameter("password") + "')";
            if (stmt.execute(query))
            {
                rs = stmt.getResultSet();
            }
            if (rs != null)//query statement SELECT
            {
                if (rs.next())
                {
                    if (rs.getInt("StatusBan")==0)
                    {
                        HttpSession session = request.getSession();
                        
                        if (rs.getInt("role") == 2)
                        {
                            out.println("<meta HTTP-EQUIV='REFRESH' content='2; url=admin.jsp'>"
                                    + "<link rel='StyleSheet' href='index.css' type='text/css' />");
                            session.setAttribute("userrole", "admin");
                            ps = (PreparedStatement) conn.prepareStatement("update user set Online = 1 where Username = ?");
                            ps.setString(1, request.getParameter("username"));
                            ps.executeUpdate();
                            session.setAttribute("username", rs.getString("username"));
                        }
                        else
                        {
                            out.println("<meta HTTP-EQUIV='REFRESH' content='0; url=home.jsp'>");
                            if (rs.getInt("role") == 1)
                            {
                                session.setAttribute("userrole", "moderator");
                                ps = (PreparedStatement) conn.prepareStatement("update user set Online = 1 where Username = ?");
                                ps.setString(1, request.getParameter("username"));
                                ps.executeUpdate();
                            }
                            else
                            {
                                session.setAttribute("userrole", "user");
                                ps = (PreparedStatement) conn.prepareStatement("update user set Online = 1 where Username = ?");
                                ps.setString(1, request.getParameter("username"));
                                ps.executeUpdate();
                            }
                            session.setAttribute("username", rs.getString("username"));
                            //globalvar.Online.updateUser(rs.getString("username"));
                        }
                        out.println("</head>");
                        out.println("<body>"
                                + "<div id='header'><img src='title.png' width='30%'></div>");
                        out.println("<div id='info'>");
                        out.println("Login with username :  " + rs.getString("username") + ".");
                        out.println("</div>");
                    }
                    else
                    {
                        out.println("</head>");
                        out.println("<body>");
                        out.println("<div id='info'>");
                        out.println("You are banned by administrator.");
                        out.println("</div>");
                    }
                }
                else
                {
                    out.println("<meta HTTP-EQUIV='REFRESH' content='2; url=index.jsp'>");
                    out.println("</head>");
                    out.println("<body>");
                    out.println("<div id='info'>");
                    out.println("Login failed, your username or password wrong.");
                    out.println("</div>");
                }
            }
            out.println("</body>");
            out.println("</html>");
            conn.close();
        }
        catch (SQLException ex)
        {
            out.println("SQLException: " + ex.getMessage());
            out.println("SQLState: " + ex.getSQLState());
            out.println("VendorError: " + ex.getErrorCode());
        }
        catch (Exception ex)
        {
            out.println(ex.toString());
        }
        finally {
            if (rs != null) {
                try {
                rs.close();
                } catch (SQLException sqlEx) { } // ignore
                rs = null;
            }
            if (stmt != null) {
                try {
                stmt.close();
                } catch (SQLException sqlEx) { } // ignore
                stmt = null;
            }
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
